<?php
class DbDriverMysql
{
	protected $link;
	protected $persist=false;
	
	static function instance($host, $user, $passwd, $db, $persist=false)
	{
		$con	=	$persist ? mysql_pconnect($host, $user, $passwd) : mysql_connect($host, $user, $passwd);
		if(!$con)
		{
			Show::error("Open connection failure [".mysqli_error()."]");
		}
		mysql_select_db($db, $con);
		mysql_query('SET NAMES utf8', $con);
		
		$obj	=	new DbDriverMysql();
		$obj->link		=	$con;
		$obj->persist	=	$persist;
		return $obj;
	}
	
	static function qu()
	{
		return '`';
	}
	
	function close()
	{
		return $this->persist ? true : mysql_close($this->link);
	}
	
	function insertId()
	{
		return mysql_insert_id($this->link);
	}
	
	function query($sql)
	{
		return mysql_query($sql, $this->link);
	}
	
	function fetchAll($result)
	{
		if(!$result) return null;
		$rows	=	array();
		while($r=mysql_fetch_assoc($result))
		{
			$rows[]	=	$r;
		}
		mysql_free_result($result);
		return $rows;
	}
	function fetchOne($result)
	{
		if(!$result) return null;
		$row	=	mysql_fetch_assoc($result);
		mysql_free_result($result);
		return $row;
	}
	
	function fields($table)
	{
		$res	=	mysql_query("SHOW FIELDS FROM {$table}", $this->link);
		if($res)
		{
			$rows	=	array();
			$pk		=	'';
			while($r=mysql_fetch_assoc($res))
			{
				if(false!==strpos($r['Type'], 'int'))
				{
					$rows[$r['Field']]	=	1;
				}
				elseif(false!==strpos($r['Type'], 'float') 
					|| false!==strpos($r['Type'], 'double') 
					|| false!==strpos($r['Type'], 'decimal'))
				{
					$rows[$r['Field']]	=	2;
				}
				else
				{
					$rows[$r['Field']]	=	0;
				}
				
				if(!$pk && $r['Key']=='PRI')
				{
					$pk	=	$r['Field'];
				}
			}
			if($pk)
			{
				$rows['_pk']	=	$pk;
			}
			mysql_free_result($res);
			return $rows;
		}
		return false;
	}
	
	function qstr($s)
	{
		return mysql_real_escape_string($s);
	}
	
	function lastError()
	{
		return mysql_error($this->link);
	}
	
	function makeLimit($s, $l)
	{
		return "LIMIT $s,$l";
	}
	
	function affectedRows()
	{
		return mysql_affected_rows($this->link);
	}
	
}
?>